package com.ideaaedi.zoo.example.springboot.sse.controller;

import com.ideaaedi.commonds.time.DateTimeConverter;
import com.ideaaedi.zoo.diy.artifact.sse.core.SsePusher;
import com.ideaaedi.zoo.example.springboot.sse.callback.DemoSsePusherCallback;
import com.ideaaedi.zoo.example.springboot.sse.util.SseUidUtil;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.util.Set;

/**
 * demo
 *
 * @author <font size = "20" color = "#3CAA3C"><a href="https://gitee.com/JustryDeng">JustryDeng</a></font> <img
 * src="https://gitee.com/JustryDeng/shared-files/raw/master/JustryDeng/avatar.jpg" />
 * @since 1.0.0
 */
@RestController
public class Demo实战Controller {

    @Resource
    private SsePusher ssePusher;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @CrossOrigin
    @RequestMapping("/demo-2-sse")
    public SseEmitter demo2Sse(@RequestHeader(value = "userId") String userId,
                               @RequestParam(value = "connectionId") String connectionId) {
        String emitterUuid = SseUidUtil.buildEmitterUuid(userId, connectionId);
        return ssePusher.connect(emitterUuid);
    }

    @CrossOrigin
    @RequestMapping("/demo-2-push")
    public String demo2Push(@RequestParam(value = "recipientUserId") String recipientUserId) {
        String keyPattern = String.format(SseUidUtil.SSE_UUID_REDIS_PREFIX, recipientUserId, "*");
        Set<String> redisKeySet = DemoSsePusherCallback.scan(stringRedisTemplate, keyPattern, 1000);
        if (CollectionUtils.isEmpty(redisKeySet)) {
            return "用户 " + recipientUserId + " 尚未进行长连接.";
        }
        for (String redisKey : redisKeySet) {
            String emitterUuid = SseUidUtil.obtainEmitterUuid(redisKey);
            ssePusher.sendMessageDistributed(emitterUuid, "hello world " + DateTimeConverter.REGULAR_DATE_TIME.now());
        }
        return "给用户 " + recipientUserId + " 发送消息完成.";
    }
    
    
}
